package com.itheima.controller;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;

@Controller
@RequestMapping("/user")
public class UserHandler {

    final
    UserDao userDao;

    public UserHandler(UserDao userDao) {
        this.userDao = userDao;
    }
    @ResponseBody
    @RequestMapping("login")
    public String userlogin(User user, HttpServletRequest request){
        HttpSession session=request.getSession(true);
        System.out.println(user.getUsername());
        User u=userDao.findUserByUsername(user.getUsername());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){

                session.setAttribute("User",u);
                System.out.println(session.getAttribute("User"));
                return "ok";
            }
        }
        return "no";
        }

        @ResponseBody
    @RequestMapping("/zhuce")
    public String userzhuce(User user){
            User u=userDao.findUserByUsername(user.getUsername());
            if(user.getUsername()==""||user.getPassword()==""||user.getPhone()==""){
                return "no2";
            }
            if (u==null){
                userDao.save(user.getUsername(),user.getPassword(),user.getPhone());
                return "ok";
            }
            return "no";
        }
        @ResponseBody
    @RequestMapping("/match")
    public String usermatch(HttpServletRequest request){
        HttpSession session=request.getSession(true);
        User u= (User) session.getAttribute("User");
            System.out.println(u);
            System.out.println(session.getAttribute("User"));
        if (u==null){
            System.out.println("error");
            return "error";
        }else {
        return "ok";
        }
        }

        @ResponseBody
    @RequestMapping("/ChangeMessage")
    public String changeMessage(User u,HttpSession session){
            User u1= (User) session.getAttribute("User");
            System.out.println(u1.getId());
            System.out.println(u.getName());
            System.out.println(u.getPhone());

        userDao.ChangeMessage(u1.getId(),u.getName(),u.getAge(),u.getPhone());
        return "ok";
        }

        @ResponseBody
    @RequestMapping("/ChangePassword")
    public String changePassowrd(HttpSession session,String oldpass,String password){
      User u= (User) session.getAttribute("User");
      User newu=userDao.findUserByUsername(u.getUsername());

      if (newu.getPassword().equals(oldpass)){
          userDao.ChangePassword(password,u.getId());
          session.setAttribute("User",newu);
          return "ok";
      }
      return "no";
        }
        @ResponseBody
    @RequestMapping("/findMessage")
    public User findMessage(HttpSession session){
            User u= (User) session.getAttribute("User");

        return  userDao.findMessageById(u.getId());

        }

        @ResponseBody
        @RequestMapping("/forgetPassowrd")
        public String forgetPassword(String username,String phone,String password){

            System.out.println(username);
            System.out.println(phone);
            System.out.println(password);
        if (username!=null){
           User u= userDao.findUserByUsername(username);
           if (u!=null){
               if (u.getPhone().equals(phone)){
                   userDao.updatePassword(password,username);
                   return "ok";
               }else {
                   return "error";
               }
           }else {
               return "error";
           }

        }else {
            return "null";
        }



        }

    @RequestMapping("/downDir")
    public void downDir(HttpSession session, HttpServletResponse response,String dirname,String username) throws FileNotFoundException {
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "static";
        User u= (User) session.getAttribute("User");
        System.out.println(u.getUsername());
        System.out.println(dirname);
        try {
            String fileName = dirname;
            String path=null;
            if (username!=null){
                 path=realPath+"/"+username+"/"+dirname;
            }
            else {
                    path=realPath+"/"+u.getUsername()+"/"+dirname;
            }
            System.out.println(path);
            File file = new File(path);
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 设置response的Header
            ContentInfo info1 = ContentInfoUtil.findExtensionMatch(fileName);
            String dirtype=info1.getMimeType();
            response.setContentType(dirtype);

            response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = response.getOutputStream();
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        }




}
